<template>
  <!-- <BaseMainSlot>
    <template v-slot:searchbox>
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
<div class="search-btn search-btns" @click.stop="queryPageList()">
  <i class="el-icon-circle-check"></i>
  <p>查询</p>
</div>
<div class="select-box-content">
  <div class="select-box-content-name">基地名称</div>
  <el-input v-model="homeBaseName" clearable @change="queryPageList" />
</div>
</el-collapse-item>
</el-collapse>
</template>
<template v-slot:btnsBar>
      <ActionBar :add-active="addActive" :del-active="delActive" :page-no="181" @add="add" @del="del" />
    </template>
<template v-slot:content>
      <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" stripe border
        height="calc(100% - 50px)" :row-key="row => {
          return row.homeBaseId;
        }
        " @selection-change="handleSelectionChange" @select="select" @select-all="selectAll">
        <el-table-column type="selection" width="55" :reserve-selection="true"
          :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">
            {{ scoped.row.homeBaseId ? scoped.$index + 1 : "" }}
          </template>
</el-table-column>
<el-table-column prop="homeBaseName" label="基地名称" />
<el-table-column prop="code" label="基地标识" />
<el-table-column prop="breedTypeStr" label="养殖类型" />
<el-table-column prop="principal" label="负责人" />
<el-table-column prop="tel" label="联系方式" />
<el-table-column prop="memo" label="说明" />
<el-table-column prop="address" label="地址" />
<el-table-column label="操作" width="250">
  <template v-if="scoped.row.homeBaseId" slot-scope="scoped">
            <div class="table-btns-box">
              <div class="table-btns edit-btns" @click="edit(scoped.row)">
                <p>修改</p>
              </div>
              <div class="table-btns del-btns" @click="delOne(scoped.row)">
                <p>删除</p>
              </div>
            </div>
          </template>
</el-table-column>
</el-table>
<Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize" @changePageSize="changePageSize"
  @changeCurrentPage="changeCurrentPage" />
<AddEditDialog ref="addEditDialog" :now-chance-stau="nowChanceStau" :title-text="titleText" :edit-object="editObject"
  :show.sync="showAddEditDialog" @closeDialog="closeDialog" @cancelDialog="cancel" />
</template>
</BaseMainSlot> -->


  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="search">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" stripe border :row-key="row => {
        return row.homeBaseId;
      }
        " @selection-change="handleSelectionChange" @select="select" @select-all="selectAll">
        <el-table-column type="selection" width="55" :reserve-selection="true"
          :selectable="(row) => { return !row.selectable }" />
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">
            {{ scoped.row.homeBaseId ? scoped.$index + 1 : "" }}
          </template>
        </el-table-column>
        <el-table-column prop="homeBaseName" label="基地名称" />
        <el-table-column prop="code" label="基地标识" />
        <el-table-column prop="breedTypeStr" label="养殖类型" />
        <el-table-column prop="principal" label="负责人">
          <template slot-scope="scoped">
            {{ scoped.row.principal || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="tel" label="联系方式" width="200">
          <template slot-scope="scoped">
            {{ scoped.row.tel || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="memo" label="说明">
          <template slot-scope="scoped">
            {{ scoped.row.memo || '--' }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址">
          <template slot-scope="scoped">
            {{ scoped.row.address || '--' }}
          </template>
        </el-table-column>
        <el-table-column label="基地图片" width="220">
          <template slot-scope="scoped">
            <el-image v-if="scoped.row.imgList && scoped.row.imgList.length > 0" class="imageStyle"
              :src="scoped.row.imgList[0]" :preview-src-list="scoped.row.imgList">
            </el-image>
            <div class="imageStyle el-icon-picture-outline" v-else></div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template v-if="scoped.row.homeBaseId" slot-scope="scoped">
            <span class="table-btns edit-btns successText" @click="edit(scoped.row)">修改</span>
            <span class="table-btns del-btns errorText" @click="delOne(scoped.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="changeCurrentPage" :page="currentPage" :size="pageSize" :total="totalSize">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <AddEditDialog ref="addEditDialog" :now-chance-stau="nowChanceStau" :title-text="titleText"
        :edit-object="editObject" :show.sync="showAddEditDialog" @closeDialog="closeDialog" @cancelDialog="cancel" />
      <el-dialog title="提示" :visible.sync="dialogVisibleSort" width="30%" :before-close="handleClose">
        <div class="draggableModule">
          <draggable v-model="draggableList">
            <div class="draggableItem" v-for="item in draggableList" :key="item.id">
              <span>{{ item.homeBaseName }}</span>
              <i class="el-icon-s-fold"></i>
            </div>
          </draggable>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleSort = false">取 消</el-button>
          <el-button type="primary" @click="saveSort">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import BtnSlot from '@/components-production-management/BtnSlot';

import draggable from 'vuedraggable'
import AddEditDialog from "./components/add-edit-dialog.vue";
import { mymixin } from "@/utils/mixin";
import { mapGetters } from 'vuex';

import homeBaseApi from "@/api/basic-info-manage/homeBase";
export default {
  name: 'HomeBaseManage',
  components: { BtnSlot, Pagination, SearchForm, MainSlot, AddEditDialog, draggable },
  mixins: [mymixin],
  data() {
    return {
      loading: false,
      dialogVisibleSort: false,
      draggableList: [],
      // 所搜条件：基地名称
      homeBaseName: "",
      userList: [],
      checkedIdList: [],
      btnList: ['add', 'delete', 'sort'],
      formItemList: [
        {
          label: '基地名称',
          type: 'input',
          param: 'homeBaseName',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
      ],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },

  watch: {},
  created() {
    this.queryPageList();
  },
  mounted() {
    this.initData();
  },
  methods: {
    search(data) {
      this.homeBaseName = data.homeBaseName;
      this.queryPageList();
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    saveSort() {
      let idList = this.draggableList.map(item => item.homeBaseId);
      homeBaseApi.saveSort(idList).then(res => {
        this.getHomeBase()
        if (res.success) {
          this.$message.success('操作成功')
          this.dialogVisibleSort = false;
          this.currentPage = 1;
          this.queryPageList();
          this.initData();
        } else {
          this.$message.warning('操作失败')
        }
      }).catch(err => {
        this.getHomeBase()
        this.$message.warning('操作失败')
      });
    },
    async initData() {
      let { data: homeBaseList } = await homeBaseApi.queryByCondition({});
      this.draggableList = JSON.parse(JSON.stringify(homeBaseList || []));
    },
    // 测试基地分页查询接口
    queryPageList() {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortStr: 'sort',
        entity: {
          homeBaseName: this.homeBaseName
        }
      };
      this.loading = true;
      homeBaseApi.queryPageByCondition(params).then(res => {
        this.loading = false;
        if (res.success === true) {
          let data = res.data || {};
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.tableData.forEach(item => {
            item.imgList = [];
            let fileIdList = item.logoId ? [item.logoId] : []
            fileIdList.forEach(id => {
              item.imgList.push(`${this.$baseurl.fileServiceUrl}base/files/preview?fileId=${id}`)
            })
          })
        }
      }).catch(err => {
        this.loading = false;
      });
    },
    // 获取当前用户可查看基地列表
    getHomeBase() {
      // 获取顶级组织结构id
      homeBaseApi.queryByUserId().then(res => {
        if (res.length == 0 || res.data == []) {
          this.$message.warning("该账户下无基地权限，请联系管理员！")
          removeToken("token")
          this.$router.push({ path: "/login" })
        } else {
          //默认第一个基地
          // setToken("companyMark", res.data[0].code);
          // setToken("homeBaseId", res.data[0].homeBaseId);
          // setToken("homeBaseType", res.data[0].homeBaseType);
          // setToken("homeBaseName", res.data[0].homeBaseName);
          sessionStorage.setItem("homeBaseList", JSON.stringify(res.data));
        }
      })
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.queryPageList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.queryPageList();
    },
    selectAll(list) {
      let notvalue = true
      list.forEach(item => {
        if (!item.homeBaseId) {
          notvalue = false
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    select(list) {
      let notvalue = true
      list.forEach(item => {
        if (!item.homeBaseId) {
          notvalue = false
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    handleSelectionChange(list) {
      this.checkedIdList = [];
      let notvalue = true
      let emptyList = []
      this.checkedIdList = list.map(item => {
        if (item.homeBaseId) {
          return item.homeBaseId
        } else {
          notvalue = false
          emptyList.push(item)
          return ""
        }
      });
      if (notvalue === false) {
        // this.$message.warning("不可选择空数据！");
        this.toggleNoSelection(emptyList)
        return
      }
      if (this.checkedIdList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },

    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.add();
      } else if (flag == 'delete') {
        this.delmessage();
      } else if (flag == 'sort') {
        this.dialogVisibleSort = true;
      }
    },
    // 单个删除
    delOne(data) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      }).then(() => {
        homeBaseApi.delById({ id: data.homeBaseId }).then(res => {
          this.getHomeBase()
          if (res.success) {
            this.$message.success("删除成功");
            this.queryPageList();
          }
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    },
    // 表格删除
    delmessage() {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      }).then(() => {
        homeBaseApi.delListById({ idList: this.checkedIdList }).then(res => {
          this.getHomeBase()
          if (res.success) {
            this.$message.success("添加成功");
            this.queryPageList();
          }
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    },
    // 添加
    add() {
      this.nowChanceStau = 'add'
      this.titleText = "添加"
      this.addActive = false;
      this.delActive = false;
      this.showAddEditDialog = true
    },
    // 修改
    edit(row) {
      if (row.homeBaseId) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = 'edit'
        this.titleText = "修改"
        this.addActive = false;
        this.delActive = false;
        this.showAddEditDialog = true
      } else {
        this.editObject = {}
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.table-btns {
  padding: 0 10px;
  cursor: pointer;
}

.imageStyle {
  height: 100px;
  width: 200px;
  border-radius: 4px;
  margin: 0 auto;
  background-color: #cecece3f;
  display: flex;
  align-items: center;
  justify-content: space-around;
  font-size: 16px;
  color: #999999;
}

.draggableModule {
  width: 100%;

  .draggableItem {
    padding: 5px 10px;
    background-color: #eeeeee;
    margin-bottom: 5px;
    display: flex;
    justify-content: space-between;
    cursor: pointer;
  }
}
</style>
